package com.ruoyi.common.utils;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

/**
 *  通过IP和子网掩码位数 来生成IP
 */
public class IpRangeGenerator {

    /**
     * 将IP地址转换为整数
      */
    public static long ipToLong(String ip) throws UnknownHostException {
        InetAddress inetAddress = InetAddress.getByName(ip);
        byte[] bytes = inetAddress.getAddress();
        long result = 0;
        for (int i = 0; i < bytes.length; i++) {
            result |= ((long) (bytes[i] & 0xFF)) << (8 * (3 - i));
        }
        return result;
    }

    // 将整数转换为IP地址
    public static String longToIp(long ip) {
        return ((ip >> 24) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." + (ip & 0xFF);
    }

    // 通过IP和子网掩码位数生成IP范围并打印所有IP
    public static List<String> generateAllIps(String ip, int subnetMask) throws UnknownHostException {
        List<String> list = new ArrayList<>();
        long ipLong = ipToLong(ip);
        // 计算子网掩码
        long mask = (0xFFFFFFFFL << (32 - subnetMask)) & 0xFFFFFFFFL;
        // 网络地址 = IP & 掩码
        long networkAddress = ipLong & mask;
        // 广播地址 = 网络地址 | (反向掩码)
        long broadcastAddress = networkAddress | (~mask & 0xFFFFFFFFL);
        
        // 起始IP地址（网络地址 + 1）
        long startIp = networkAddress + 1;
        // 结束IP地址（广播地址 - 1）
        long endIp = broadcastAddress - 1;

        // 打印所有IP地址
        for (long currentIp = startIp; currentIp <= endIp; currentIp++) {
            list.add(longToIp(currentIp));
        }
        return  list;
    }

    public static void main(String[] args) throws UnknownHostException {
        ten2two(24);
    }

    private static String ten2two(int ten){
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 32; i++) {
            if (ten>0){
                sb.append("1");
                ten--;
            }else{
                sb.append("0");
            }
        }
        System.out.println(sb);
        return sb.toString();
    }
}
